package com.spzx.cart.listener;

import com.rabbitmq.client.Channel;
import com.spzx.cart.service.CartService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class SpzxCartMqListener {
    @Resource
    CartService cartService;
    //通过队列绑定 订单交换机， 路由key需要使用提交订单成功消息的路由key
    @RabbitListener(
            bindings = {
                @QueueBinding(
                        value = @Queue(value = "spzx.cart.order.submit.queue",
                                durable = "true"),
                        //使用订单服务的交换机：如果已存在 直接使用，不存在新创建
                        // 已存在 如果本次配置和以前的不一样  会报错
                        exchange = @Exchange(value = "spzx.order.exchange" ,
                            type = ExchangeTypes.TOPIC ),
                        key = "spzx.order.submit.success"
                )
            }
    )
    public void submitOrderConsumer(Channel channel , Message message, Map<String,Object> map) throws IOException {
        try {
            //1、消费消息的业务
            //删除购物车中订单的购物项
            long userId = Long.parseLong(map.get("userId").toString());
            cartService.deleteCheckedCartInfo(userId);

            //2、手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            //重试消费  或者 丢弃消息
            if(message.getMessageProperties().isRedelivered()){
                //第二次消费失败： 第一次失败会进入else让消息重新回到队列中 可以继续消费
                //丢弃消息： 会变为死信
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                        false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                        false,true);
            }


        }


    }

}
